<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>生成投票</title>
  <link href="https://cdn.bootcss.com/weui/1.1.2/style/weui.css" rel="stylesheet">
  <link href="https://cdn.bootcss.com/jquery-weui/1.2.0/css/jquery-weui.css" rel="stylesheet">
  <style>
    html,body,p,ul,li,main,section{
      margin: 0;
      padding: 0;
    }
    html,body {
      background-color: #f3f4f7;
      -webkit-tap-highlight-color: transparent;
    }
    section {
      padding: 0 5px;
    }
    .topic-wrapper {
      border: 1px solid #ccc;
      border-radius: 5px;
      margin-bottom: 10px;
    }
    .select-item {
      width: 90%;
      margin-left: 8px;
    }
    .btn-submit {
      width: 80%;
      margin: auto;
      margin-top: 35px;
    }
    .weui-icon-addition {
      position: relative;
      display: inline-block;
      width: 10px;
      height: 10px;
      padding: 3px;
      border: 1px solid #586C94;
      border-radius: 50%;
      /* background-color: #586C94; */
      background-clip: content-box;
    }
    .p_add-select-item {
      display: inline-block;
      margin-left: 8px;
    }
    .weui-icon-addition::before {
      content: '';
      position: absolute;
      width: 10px;
      height: 0;
      border: 1px solid #586C94;
      box-sizing: border-box;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      /* background-color: #586C94; */
    }
    .weui-icon-addition::after {
      content: '';
      position: absolute;
      width: 10px;
      height: 0;
      border: 1px solid #586C94;
      box-sizing: border-box;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      transform: rotate(90deg);
    }
    .weui-icon-reduce::before {
      position: absolute;
      content: '';
      width: 10px;
      height: 0;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      box-sizing: border-box;
      border: 1px solid #f00;
      color: red;
    }
    .weui-icon-reduce {
      position: relative;
      display: inline-block;
      width: 10px;
      height: 10px;
      padding: 3px;
      border: 1px solid #f00;
      border-radius: 50%;
      /* background-color: #f00; */
      background-clip: content-box;
    }

    .close {
      display: inline-block;
      transform: rotate(45deg);
    }

    .delete-topic {
      font-size: 12px;
      display: block;
      padding: 5px 0;
      margin-bottom: 0;
      text-align: center;
      color: #999;
      border-top: 1px solid #eee;
      border-bottom: 1px solid #eee;
      background-color: #eee;
    }
    #add-topic {
      color: #586C94;
      text-align: center;
    }

    .checkbox-s {
      width: 15px;
      color: #586c94;
      border: 0;
      border: 1px solid #586C94;
      border-radius: 50%;
      text-align: center;
    }

    .flex-justify-space-between {
      justify-content: space-between;
    }
  </style>
</head>

<body>
  <main>
    <section>
      <div class="weui-cells__title"></div>
      <div class="weui-cells weui-cells_form vote-box">
        <div class="topic-wrapper">
          <div class="weui-cell weui-cell_access flex-justify-space-between">
            <div class="weui-cell___bd">
              <input class="weui-input select-item" type="tel" placeholder="投票标题(必填)">
            </div>
            <div class="weui-cell__ft checkbox-box">
              <input type="text" class="checkbox-s" id="checkbox-s" placeholder="1" />
            </div>
          </div>
          <div class="select-group-item">
            <div class="weui-cell">
              <div class="weui-cell__hd">
              </div>
              <div class="weui-cell__bd">
                <i class="weui-icon-reduce"></i><input class="weui-input select-item" type="text" placeholder="选项">
              </div>
            </div>
            <div class="weui-cell">
              <div class="weui-cell__hd">
              </div>
              <div class="weui-cell__bd">
                <i class="weui-icon-reduce"></i><input class="weui-input select-item" type="text" placeholder="选项">
              </div>
            </div>
          </div>
          <a href="javascript:void(0);" class="weui-cell weui-cell_link">
            <div class="weui-cell__bd add-select-item"> <i class="weui-icon-addition"></i>
              <p class="p_add-select-item">添加选项</p>
            </div>
          </a>
          <div class="weui-cells__title delete-topic"><span class="close">+</span>删除本题</div>
        </div>
      </div>
      <a href="javascript:void(0);" class="weui-cell_link">
        <div class="weui-cells__title" id="add-topic">+ 添加题目</div>
      </a>
      <div class="weui-cells weui-cells_form">
        <div class="weui-cell">
          <div class="weui-cell__hd">
            <label for="datetime-picker" class="weui-label">截止日期</label>
          </div>
          <div class="weui-cell__bd">
            <input class="weui-input" type="text" id="datetime-picker" readonly />
          </div>
        </div>
        <div class="weui-cell weui-cell_switch">
          <div class="weui-cell__bd">匿名投票</div>
          <div class="weui-cell__ft">
            <input class="weui-switch" id="isAnonymous" type="checkbox">
          </div>
        </div>
      </div>
    </section>
    <section class="btn-submit">
      <a href="javascript:;" class="weui-btn weui-btn_primary" id="submit">完成</a>
    </section>
    <section>
    </section>
  </main>
  <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
  <!-- <script src="https://cdn.bootcss.com/jquery-weui/1.2.0/js/jquery-weui.js"></script> -->
  <script src="__PUBLIC__/poll/js/jquery-weui.js"></script>
  <!-- 如果使用了某些拓展插件还需要额外的JS -->
  <script src="https://cdn.bootcss.com/jquery-weui/1.2.0/js/swiper.js"></script>
  <script src="https://cdn.bootcss.com/jquery-weui/1.2.0/js/city-picker.js"></script>
  <!-- <script src="__PUBLIC__/poll/js/app.js"></script> -->
  <script>
    $(function () {
      /**
       * * 对Date的扩展，将 Date 转化为指定格式的String
       * * 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
       * * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
       * * 例子：
       * * (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
       * * (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
       */
      Date.prototype.Format = function (fmt) {
        var o = {
          "M+": this.getMonth() + 1, //月份
          "d+": this.getDate(), //日
          "h+": this.getHours(), //小时
          "m+": this.getMinutes(), //分
          "s+": this.getSeconds(), //秒
          "q+": Math.floor((this.getMonth() + 3) / 3), //季度
          "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o) {
          if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : (
            "00" + o[k]).substr(("" + o[k]).length));
        }
        return fmt;
      };

      var time = new Date();
      var nowTime = time.Format('yyyy-MM-dd hh:mm');
      var nowYear = time.getFullYear();
      var nowMonth = time.getMonth();
      var choosableMonths = [];
      var minTime = time.Format('yyyy-MM-dd');
      for (var i = nowMonth; i <= 12; i++) {
        choosableMonths.push(i);
      }
      $("#datetime-picker").val(nowTime);
      $("#datetime-picker").datetimePicker({
        title: '截止日期',
        // 截止时间只能选择未来的时间
        min: minTime
        // years: [nowYear],
        // monthes: choosableMonths
      });

      // 添加题目
      $('#add-topic').click(function () {
        var topicTmp =
          `<div class="topic-wrapper">
              <div class="weui-cell weui-cell_access flex-justify-space-between">
                <div class="weui-cell___bd">
                  <input class="weui-input select-item" type="tel" placeholder="投票标题(必填)">
                </div>
                <div class="weui-cell__ft checkbox-box">
                  <input type="text" class="checkbox-s" placeholder="1" />
                </div>
              </div>
              <div class="select-group-item">
                <div class="weui-cell">
                  <div class="weui-cell__hd"></div>
                  <div class="weui-cell__bd">
                    <i class="weui-icon-reduce"></i><input class="weui-input select-item" type="text" placeholder="选项">
                  </div>
                </div>
                <div class="weui-cell">
                  <div class="weui-cell__hd"></div>
                  <div class="weui-cell__bd">
                    <i class="weui-icon-reduce"></i><input class="weui-input select-item" type="text" placeholder="选项">
                  </div>
                </div>
              </div>
              <a href="javascript:void(0);" class="weui-cell weui-cell_link">
                <div class="weui-cell__bd add-select-item">
                  <i class="weui-icon-addition"></i>
                  <p class="p_add-select-item">添加选项</p>
                </div>
              </a>
              <div class="weui-cells__title delete-topic"><span class="close">+</span>删除本题</div>
            </div>`;

        $('.vote-box').append(topicTmp);

        $($(this).parent().prev().last().find('.checkbox-box')).trigger('click');
      });

      $('.vote-box').on('click', '.delete-topic', function (evt) {
        if (evt.currentTarget.parentNode && evt.currentTarget.parentNode.parentNode.children.length > 1) {
          console.log(evt.currentTarget.parentNode.parentNode.children.length);
          $(evt.currentTarget.parentNode).remove();
        }
      });

      var itemSelectArray;
      // 添加选项
      $('.vote-box').on('click', '.add-select-item', function (evt) {
        var selectTmp = '<div class="weui-cell">' + '<div class="weui-cell__hd">' + '</div>' +
          '<div class="weui-cell__bd">' +
          '<i class="weui-icon-reduce"></i><input class="weui-input select-item" type="text" placeholder="选项">' +
          '</div>' + '</div>';
        var selectItem = $('.select-group-item .weui-cell').clone()[0] || selectTmp;
        $(selectItem).find('input').val('').attr('placeholder', '选项');
        $(evt.currentTarget.parentNode.parentNode.children[1]).append(selectItem);
        console.log($(this).parent().parent().find('.checkbox-box'));

        // fixed 自动触发一次点击事件，解决需要点击两次的bug
        $($(this).parent().parent().find('.checkbox-box')).trigger('click');
        console.log($(this).parent().parent().find('.checkbox-box'));
      });

      // 删除选项
      $('.vote-box').on('click', '.weui-icon-delete, .weui-icon-reduce', function (evt) {
        if (evt.currentTarget.parentNode.parentNode.parentNode.childElementCount > 2) {
          $(evt.currentTarget.parentNode.parentNode).remove();
        }
      });

      $('#submit').click(function () {
        var postData = [];
        var selectItem = $('.select-item');
        // [].map.call($('.select-item'), function (i) {
        //   console.log(i)
        // })

        $.map($('.vote-box .topic-wrapper'), function (topic, topicIndex) {
          // console.log(topic)
          var tmp = [];
          var itemData = [];
          $.map($(topic).find('.select-item'), function (item, itemIndex) {
            // console.log(itemIndex);
            var a = $($(item).find('.select-item')[itemIndex]);
            // console.log(a.val());
            itemData.push({
              "id": itemIndex,
              "name": $(item).val(),
              "value": itemIndex
            });
          });
          postData.push({
            "id": topicIndex,
            "name": $(topic).find('input').eq(0).val(),
            "value": topicIndex,
            "data": itemData
          });
          $('#datetime-picker').val();
        });

        var data = {
          "expiration": $('#datetime-picker').val(),
          "isAnonymous": $('#isAnonymous').is(':checked'),
          "vote": postData
        };

        console.log(data);
        $.ajax({
          type: "POST",
          url: "__CONTROLLER__/saveListDataIndex",
          data: data,
          dataType: "json",
          success: function success(response) {
            console.log(response);
            if (response.errcode == 0) {
              console.log(data);
              $.alert({
                title: '',
                text: response.msg,
                onOK: function onOK() {
                  location.href = '__CONTROLLER__/poll/list_id/' + response.data;
                }
              });
            } else {
              $.alert(response.msg);
            }
          }
        });
      });

      /** 
       * * 控制单选多选
       */
      $('.vote-box').on('click', '.checkbox-box', function (evt) {
        var $this = $(this);
        // 获取选项数
        var selectGroupItem = $(this).parents('.topic-wrapper').children('.select-group-item');
        var itemNum = selectGroupItem.find('.select-item').length;
        itemSelectArray = Array.from({
          length: itemNum
        }).map(function (v, k) {
          return k + 1;
        });

        $($(this).children()).picker({
          title: '设置可选数',
          cols: [{
            textAlign: 'center',
            values: itemSelectArray ? itemSelectArray : [1, 2]
          }],
          defaultValue: [1],
          onClose: function onClose(picker) {
            console.log($($this).children().val());
          }
        });

        /**
         * * ref https://github.com/lihongxun945/jquery-weui/issues/341
         * ! fixed 
         */
        if ($($(this).children()).data('picker').cols[0]) {
          $($(this).children()).data('picker').cols[0].values = itemSelectArray ? itemSelectArray : [1, 2];
        }
      });

      // 加载完成自动触发一次
      $('.checkbox-box').trigger('click');
    });
  </script>
</body>

</html>